package org.chz.entity;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Getter
@Setter
@NoArgsConstructor
public class WebPage implements Comparable {
    private int docId;
    private String docTitle;
    private String docUrl;
    private String docContent;
    private double cosine;

    public WebPage(int docId, int index, int offset, double cosine) {
        this.docId = docId;
        this.cosine = cosine;
        readPage(index, offset);
    }

    void readPage(int idx, int oft) {
        try (InputStream inputStream = getClass().
                getClassLoader().
                getResourceAsStream("newripepage2.dat")) {

            // 跳过指定的字节数
            inputStream.skip(idx);

            // 读取指定长度的数据
            byte[] buffer = new byte[oft];
            int bytesRead = inputStream.read(buffer, 0, oft);

            if (bytesRead == -1) {
                throw new IllegalArgumentException("无法读取指定长度的数据！");
            }

            // 打印读取到的数据
            String data = new String(buffer, 0, bytesRead, StandardCharsets.UTF_8);

            // 将读取的数据转换为字节数组输入流
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer, 0, bytesRead);

            // 解析XML数据
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(byteArrayInputStream);

            // 获取XML标签内容
            docTitle = document.getElementsByTagName("title").item(0).getTextContent();
            docUrl = document.getElementsByTagName("link").item(0).getTextContent();
            docContent = document.getElementsByTagName("content").item(0).getTextContent();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int compareTo(Object o) {
        WebPage page = (WebPage) o;

        if (page.cosine == this.cosine) {
            return 0;
        } else if (page.cosine > this.cosine) {
            return 1;
        }
        return -1;
    }

}
